import os
import pandas as pd
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def generate_level_scores(df, secondary_weights, meta_cols, output_dir, method_name):
    # 六大一级维度对应的二级指标
    level_mapping = {
        'Level1数字基础设施': ['S1', 'S2', 'S3'],
        'Level2数据治理环境': ['D1', 'D2', 'D3'],
        'Level3数字金融服务': ['F1', 'F2', 'F3'],
        'Level4数字创新支撑': ['T1', 'T2', 'T3'],
        'Level5数字人力资本': ['Q1', 'Q2', 'Q3'],
        'Level6法制环境保障': ['L1', 'L2', 'L3'],
    }

    required_metrics = [metric for level in level_mapping.values() for metric in level]
    
    # 验证输入数据
    if not all(col in df.columns for col in meta_cols):
        missing_cols = [col for col in meta_cols if col not in df.columns]
        raise ValueError(f"缺失必需的列: {missing_cols}")
    
    # 创建结果副本，避免修改原始数据
    df_level = df[meta_cols].copy()
    
    # 获取二级指标权重文件名，确保每种方法使用单独的权重计算
    unique_identifier = f"{method_name}_{sum(hash(metric) for metric in meta_cols)}"
    unique_identifier = unique_identifier[:16]  # 限制长度以防过长
    
    for level, cols in level_mapping.items():
        if not all(col in meta_cols for col in cols):
            raise ValueError(f"一级指标 {level} 的二级指标不在 meta_cols 中")
        
        try:
            # 从传入的二级指标权重中取出对应权值，并处理NaN
            sub_weights = secondary_weights.loc[cols].fillna(0).values.astype(float)
            if any(w <= 0 for w in sub_weights):
                logger.warning(f"{level} 的部分权重无效或接近零: {sub_weights}")
            
            df_level[level] = df_level[cols].values @ sub_weights
            level_weight = sub_weights.sum()
            if level_weight <= 0:
                logger.warning(f"{level} 的权重总和为零或无效: {sub_weights}")
            
            df_level.loc[:, level] = df_level[cols].values @ sub_weights
            
            # 一级指标的权重
            level_weights[level] = level_weight
            logger.info(f"计算完成: {level} (权重: {level_weight:.4f})")
            
        except Exception as e:
            logger.error(f"计算 {level} 时出错: {str(e)}")
            raise

    # 检查是否成功计算了所有一级指标
    calculated_levels = [k for k in level_mapping.keys() if k in df_level.columns]
    if len(calculated_levels) != len(level_mapping):
        logger.warning(f"仅成功计算了 {len(calculated_levels)} 个一级指标")

    # 检查权重总和是否接近1
    total_weight = sum(level_weights.values())
    if abs(total_weight - 1.0) > 0.0001:
        logger.warning(f"所有一级指标权重总和为 {total_weight:.4f}，而非预期的1.0")

    # 创建一级指标权重DataFrame
    level_weights_df = pd.DataFrame({
        '指标': list(level_weights.keys()),
        '权值': list(level_weights.values())
    })
    
    # 保存标准化的权值
    normalized_weights = level_weights_df.set_index('指标')['权值'] / total_weight

    # 文件路径
    score_file = os.path.join(output_dir, f"{method_name}_level_scores.csv")
    weight_file = os.path.join(output_dir, f"{method_name}_level_weights.csv")
    
    df_level.to_csv(score_file, index=False, encoding='utf-8-sig')
    level_weights_df.to_csv(weight_file, index=False, encoding='utf-8-sig')

    return df_level, normalized_weights, score_file

